<template>
  <div>
    <div>
      <mavon-editor ref="md" v-model="formNew.content" :ishljs="true" @imgAdd="imgAdd" style="height: 350px; z-index: 0" />
      <el-button style="float: right; margin-top: 10px" type="primary" @click="handleAdd">新增<i class="el-icon-circle-plus-outline"></i></el-button>
    </div>
    <div style="font-size: 24px; color: #409EFF; margin-top: 50px">
      <i class="el-icon-folder"></i><el-button type="text" style="font-size: 24px" @click="loadATime">我的其他文章</el-button>
    </div>
    <div v-if="moreMyArticle">
      <div style="margin-top: 12px">
        <el-input style="width: 200px" placeholder="请输入标题" suffix-icon="el-icon-search" v-model="name"></el-input>
        <el-button style="margin-left: 5px" type="primary" @click="load">搜索</el-button>
        <el-button style="margin-left: 5px" type="warning" @click="reset">重置</el-button>
      </div>
      <div style="margin: 6px 0">
        <el-popconfirm title="确认批量删除吗?" @confirm="delBatch">
          <template #reference>
            <el-button type="danger" >批量删除<i class="el-icon-remove-outline"></i></el-button>
          </template>
        </el-popconfirm>
      </div>
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="名称" ></el-table-column>
        <el-table-column  label="文章内容" >
          <template slot-scope="scope">
            <el-button @click="view(scope.row.content)" type="primary">查看内容</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="createTime"  label="发布时间" >
<!--          <template slot-scope="scope">-->
<!--            {{ new Date(scope.row.createTime).toLocaleString('zh', { hour12: false }).replaceAll('/', '-') }}-->
<!--          </template>-->
        </el-table-column>
        <el-table-column prop="like" label="点赞数" ></el-table-column>
        <el-table-column  label="头像" width="100">
          <template slot-scope="scope">
            <img  :src="scope.row.coverUrl" style="width: 55px; height: 35px"/>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="100">
          <template #default = "scope">
            <el-button size="small" type="text" @click="handleEdit(scope.row)"  style="padding: 2px">编辑</el-button>
            <el-popconfirm title="确认删除吗?" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button size="small"  type="text" style="padding: 2px">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 2px 0">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[2, 4, 6, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="文章信息" :visible.sync="dialogFormNewVisible" width="60%">
      <el-form :model="formNew" label-width="80px" >
        <el-form-item label="文章封面">
          <el-upload
              class="cover-uploader"
              action="http://localhost:9090/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess1">
            <img v-if="formNew.coverUrl" :src="formNew.coverUrl" class="cover">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章标题">
          <el-input v-model="formNew.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormNewVisible = false; formNew = {}">取 消</el-button>
        <el-button type="primary" @click="saveNew">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="文章信息" :visible.sync="dialogFormVisible" width="60%">
      <el-form :model="form" label-width="80px" >
        <el-form-item label="文章封面">
          <el-upload
              class="cover-uploader"
              action="http://localhost:9090/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <img v-if="form.coverUrl" :src="form.coverUrl" class="cover">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章标题">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容">
          <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="imgAdd"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false; form = {}">取 消</el-button>
        <el-button type="primary" @click="resave">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="文章内容" :visible.sync="dialogContentVisible" width="60%">

      <div>
        <mavon-editor
            class="md"
            :value="content"
            :subfield="false"
            :defaultOpen="'preview'"
            :toolbarsFlag="false"
            :editable="false"
            :scrollStyle="true"
            :ishljs="true"
        />
      </div>

    </el-dialog>
  </div>
</template>

<style>
.cover-uploader {
  text-align: center;
  padding-bottom: 10px;
}
.cover-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 98px;
  line-height: 98px;
  text-align: center;
}
.cover {
  border-radius: 10px;
  width: 158px;
  height: 98px;
  display: block;
}
</style>

<script>
import axios from "axios";

export default {
  name: "ArticleEdit",
  data() {
    return {
      tableData: [],
      total:0,
      name:"",
      pageSize:4,
      pageNum:1,
      form:{},
      dialogFormVisible: false,
      dialogContentVisible: false,
      dialogFormNewVisible: false,
      multipleSelection: [],
      formNew: {},
      content:'',
      moreMyArticle: false,
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },
  created() {
    this.load();
  },
  methods :{
    view(content) {
      this.content = content
      this.dialogContentVisible = true
    },
    loadATime() {
      // if (this.tableData === null) {
      //   this.load()
      // }
      this.moreMyArticle = !this.moreMyArticle
    },
    // 请求分页查询数据
    load(){
      this.request.get("article/page",{
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          userId: this.user.id
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })

    },
    // 保存
    saveNew() {
      this.request.post("/article", this.formNew).then(res =>{
        if(res.data) {
          this.$message.success("保存成功")
        } else {
          this.$message.error("保存失败")
        }
        this.load()
      })
      this.dialogFormVisible = false;
      this.formNew = {};
    },

    // 保存
    resave() {
      // console.log(this.form)
      this.request.post("/article", this.form).then(res =>{
        if(res.data) {
          this.$message.success("保存成功")
        } else {
          this.$message.error("保存失败")
        }
        this.load()
      })
      this.dialogFormVisible = false;
      this.form = {};
    },
    //编辑
    handleEdit(row){
      this.form = JSON.parse(JSON.stringify(row)) //深拷贝
      this.form.id = row.id;
      this.dialogFormVisible = true;
    },
    // 删除
    handleDelete(id){
      this.request.delete("/article/" + id).then(res => {
        if (res.data) {
          this.$message.success("删除成功"
          )
        } else {
          this.$message.error("删除失败")
        }
        this.load()
      })
    },
    //实现批量选择
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    //批量删除
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id) // 得到每个选择对象的 id
      console.log(ids)
      this.request.post("/article/del/batch", ids).then(res => {
        if (res.data) {
          this.$message.success("批量删除成功")
        } else {
          this.$message.error("批量删除失败")
        }
        this.load()
      })
    },

    // 改变页大小
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load();
    },
    // 改变当前页
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load();
    },
    // 重新设置搜索框
    reset() {
      this.name = ""
      this.load()
    },
    // 打开新增表单
    handleAdd() {
      this.dialogFormNewVisible = true
      // this.form = {}
    },
    handleAvatarSuccess1 (res) {
      this.formNew.coverUrl = res
      console.log("nihao")
      console.log(this.formNew.coverUrl)
    },
    handleAvatarSuccess (res) {
      this.form.coverUrl = res
    },
    // 将图片上传到服务器，返回地址替换到md中
    imgAdd(pos, $file){
      let $vm = this.$refs.md
      //第一步，将图片上传到服务器
      const fromData = new FormData();
      fromData.append('file', $file);
      axios({
        url: 'http://localhost:9090/file/upload',
        method: 'post',
        data: fromData,
        headers: {'Content-Type': 'multipart/form-data'},
      }).then((res) => {
        // 第二步，将返回的 url 替换到文本原位置![...](./0) -> ![...](url)
        $vm.$img2Url(pos, res.data)
      })
    },
  }
}
</script>